package pl.umk.mat.fred.unicore.urc.storagemanagement.actions.findNavigation;

import java.util.ListIterator;

import org.eclipse.jface.action.Action;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;

import pl.umk.mat.fred.unicore.urc.storagemanagement.actions.FindAction.SearchResult;
import pl.umk.mat.fred.unicore.urc.storagemanagement.actions.findNavigation.NextSearchResultAction.Direction;
import pl.umk.mat.fred.unicore.urc.storagemanagement.views.StorageBrowserView;

public class PrevSearchResultAction extends Action {

	private ListIterator<SearchResult> itr;
	private StorageBrowserView view;
	
	public PrevSearchResultAction(StorageBrowserView view) {
		super();
		this.view = view;
		this.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_TOOL_BACK));
	}
	
	public void run() {
		System.out.println("Prev");
		if (Direction.FORWARD.equals(view.getNextSearchResultAction().getLastDirection())
				&& itr.hasPrevious()) {
			itr.previous();
		}
		if (itr != null) {
			if (itr.hasPrevious()) {
				SearchResult result = itr.previous();
				CommonTools.trySelectTreeNode(this, view, view.getNextSearchResultAction().getListOfMulticatalogs(), result);
				if (!itr.hasPrevious()) {
					this.disable();
				}
			} else {
				this.disable();
				view.getNextSearchResultAction().enable();
			}
			if (itr.hasNext()) {
				view.getNextSearchResultAction().enable();
			} else {
				view.getNextSearchResultAction().disable();
			}
		}
		view.getNextSearchResultAction().setLastDirection(Direction.BACKWARD);
	}
	
	public void enable() {
		this.setEnabled(true);
		this.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_TOOL_BACK));
	}
	
	public void disable() {
	  this.setEnabled(false);
	  this.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_TOOL_BACK_DISABLED));
  }
	
	public void setIterator(ListIterator<SearchResult> itr) {
	  this.itr = itr;
  }
}
